package cn.bang.mod

import java.io.File

fun printlnErr(message: Any?) = System.err.println(message)

val String.strBlocks: List<String>
    get() {
        return this.replace(";", "").split('+').map { it.trim() }
    }

val String.valuables: List<String>
    get() {
        return this.strBlocks.asSequence().filter { (it.first() != '"') && (it.last() != '"') }.toList()
    }

val String.texts: List<String>
    get() {
        return this.strBlocks.filter { (it.first() == '"') && (it.last() == '"') }
    }

val String.isValuable: Boolean
    get() {
        return (this.trim().first() != '"') && (this.trim().last() != '"')
    }

val String.hasValuable: Boolean
    get() {
        return this.valuables.isNotEmpty()
    }

fun String.carefulReplace(oldValue: String, newValue: String): String {
    return if (this.contains(oldValue)) {
        this.replace(oldValue, newValue)
    } else {
        println(
            """
            无法替换，因为文本中找不到要替换的值
            oldValue(Origin): $oldValue 
            newValue(Local): $newValue
            
        """.trimIndent()
        )
        this
    }
}

/**
 * 将文本模板化：hello " + AKA.NAME;  =>  "hello " + {0};
 */
fun String.toTemplate(): String {
    var index = 0
    return this.strBlocks
        .map { word ->
            if (word.isValuable)
                "${word.leftTrimmedString()}{${index}}${word.rightTrimmedString()}".also { index++ }
            else word
        }
        .joinToString(separator = "+", postfix = ";")
}

/**
 * 填充文本的变量，面对两种文本的填充方式
 * "hello " + {0};  => 你好 世界;
 * hello " + AKA.NAME;  =>  "hello "; + {0} => 你好 世界;
 */
fun String.fillVariables(originVariables: List<String>): String =
    // 这里做的比较简单
    originVariables.foldIndexed(
        if ('{' in this) this else this.toTemplate()
    ) { index, acc, originVariable ->
        acc.replace("{$index}", originVariable)
    }

// 截取字符串左边为空白的字符串
fun String.leftTrimmedString(): String {
    val trimmed = this.trimStart()
    val leftMarginLength = this.indexOf(trimmed)
    return this.substring(0, leftMarginLength)
}

// 截取字符串右边为空白的字符串
fun String.rightTrimmedString(): String {
    val trimmed = this.trimEnd()
    val rightMarginLength = this.length - (trimmed.length + this.indexOf(trimmed))
    return this.substring(this.length - rightMarginLength, this.length)
}

infix fun String.sep(str: String) = this + File.separator + str


val CHINESE_SYMBOLS = arrayListOf(
    '；',
    '”',
    '。',
    '’',
    '：',
    '，',
    '、',
    '？',
    '（',
    '）'
)


fun isTextNeedLocalization(text: String) =
    ('"' in text)
            && ("Debug.Log" !in text)
            && ("=" in text || "+=" in text)
            && (text.last() == ';')
